package com.hamilton.erik.pt.mobile.android;

import java.text.ParseException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.core.model.Note;
import com.hamilton.erik.pt.core.util.DateTimeUtil;
import com.hamilton.erik.pt.mobile.android.app.DateTimePickerDialog;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.ResultUtil;

public class EditNoteActivity extends EditDataActivity {

	private final int DATE_PICKER_DIALOG_ID = 0;
	
	private Animal animal;
	private Note note;
	private String titleNoteType;
	private String baseRestPath;
	private ProgressDialog progressDialog = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_note);

		findViewById(R.id.note_edit_time_field).setOnClickListener(
				new OnClickListener() {
					@SuppressWarnings("deprecation")
					@Override
					public void onClick(View view) {
					    showDialog(DATE_PICKER_DIALOG_ID);
					}
				});
		
		findViewById(R.id.note_edit_save_edit_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						save();
					}
				});
		
		findViewById(R.id.note_edit_cancel_edit_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						cancel();
					}
				});
		
		animal = (Animal) getIntent().getSerializableExtra(
				getString(R.string.extra_animal_object));

		titleNoteType = getIntent()
							.getStringExtra(
									getString(R.string.extra_note_title_type));

		if(!TextUtils.isEmpty(animal.getName())) {
			StringBuilder titleBuilder = new StringBuilder("Editing ")
												.append(animal.getName())
												.append("'s");
			if(titleNoteType != null) {
				titleBuilder.append(" ").append(titleNoteType);
			}
			
			titleBuilder.append(" Note");
			
			setTitle(titleBuilder.toString());
		}

		baseRestPath = getIntent().getStringExtra(
							getString(R.string.extra_note_base_rest_path));
		
		note = (Note) getIntent().getSerializableExtra(
								getString(R.string.extra_note_object));

		populateFields();
	}

	protected void populateFields() {
		if (note != null) {
			String temp;
			
			temp = note.getTitle();
			if (!TextUtils.isEmpty(temp)) {
				EditText titleEditText = (EditText) findViewById(R.id.note_edit_title_field);
				titleEditText.setText(temp);
			}

			temp = note.getDate();
			if (!TextUtils.isEmpty(temp)) {
				EditText dateEditText = (EditText) findViewById(R.id.note_edit_time_field);
				dateEditText.setText(temp);
			}

			temp = note.getNote();
			if (!TextUtils.isEmpty(temp)) {
				EditText noteEditText = (EditText) findViewById(R.id.note_edit_note_field);
				noteEditText.setText(temp);
			}
		}
	}
	
	protected boolean validateFields() {
		boolean valid = true;
		View focusView = null;
				
		EditText titleField = ((EditText) findViewById(R.id.note_edit_title_field));
		if (TextUtils.isEmpty(titleField.getText().toString())) {
			titleField.setError(getString(R.string.error_field_required));
			focusView = titleField;
			valid = false;
		}
		
		EditText noteField = ((EditText) findViewById(R.id.note_edit_note_field));
		if (TextUtils.isEmpty(noteField.getText().toString())) {
			noteField.setError(getString(R.string.error_field_required));
			focusView = noteField;
			valid = false;
		}
		
		if (!valid) {
			focusView.requestFocus();
		}
		
		return valid;
	}
	
	protected void save() {
		
		if(validateFields()) {
			StringBuilder url = new StringBuilder(baseRestPath);
			url.append("/upsert/note");
			
			Map<String, String> params = new HashMap<String, String>();
			String temp;
			
			if(note.getId() != null) {
				params.put("id", note.getId().toString().trim());
			}
			
			if(note.getReferenceId() != null) {
				params.put("referenceId", note.getReferenceId().toString().trim());
			}
			
			temp = ((EditText)findViewById(R.id.note_edit_title_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("title", temp);
				note.setTitle(temp);
			}
			
			temp = ((EditText)findViewById(R.id.note_edit_note_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("body", temp);
				note.setNote(temp);
			}
			
			temp = ((EditText)findViewById(R.id.note_edit_time_field)).getText().toString().trim();
			if(!TextUtils.isEmpty(temp)) {
				params.put("date", temp);
				note.setDate(temp);
			}
			
			if (progressDialog == null) {
		        progressDialog = new ProgressDialog(this);
		        progressDialog.setTitle(getString(R.string.progress_uploading_title));
		        progressDialog.setMessage(getString(R.string.edit_note_progress_saving_note));
		    }
		    progressDialog.show();
		    
			VolleyJsonRestClient.getClient()
					.putJsonObject(
							url.toString(),
							new SaveSuccessListener(), 
							new DisplayErrorErrorListener(this, progressDialog),
							params);
		}
	}
	
	protected void cancel() {
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_note, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			case R.id.action_edit_note_save :
				save();
				return true;
			default :
				return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		
			case DATE_PICKER_DIALOG_ID :
				EditText timeEditText = (EditText) findViewById(R.id.note_edit_time_field);
				Calendar timeCalendar = Calendar.getInstance();
				if(!TextUtils.isEmpty(
						timeEditText.getText().toString())) {
					try {
						timeCalendar.setTime(
								DateTimeUtil.standardDateTimeStringToDate(
										timeEditText.getText().toString()));
					} catch (ParseException ignore) {
						// Nothing we can do here, use the default calendar instance
						Log.d("EditNoteActivity", "Unable to pare standard date to string - " + ignore.getMessage());
					}
				}
				
				DateTimePickerDialog timeDtpd = new DateTimePickerDialog(this, 
						timeDateTimeSetListener,
						timeCalendar.get(Calendar.YEAR),
						timeCalendar.get(Calendar.MONTH),
						timeCalendar.get(Calendar.DAY_OF_MONTH),
						timeCalendar.get(Calendar.HOUR_OF_DAY),
						timeCalendar.get(Calendar.MINUTE));
				
				return timeDtpd;
		}
		
		return null;
	}

	private DateTimePickerDialog.OnDateTimeSetListener timeDateTimeSetListener =
			new DateTimePickerDialog.OnDateTimeSetListener() {
				
				@Override
				public void onDateTimeSet(DatePicker datePicker, TimePicker timePicker,
						int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minute) {
					Calendar calendar = Calendar.getInstance();
					calendar.set(Calendar.YEAR, year);
					calendar.set(Calendar.MONTH, monthOfYear);
					calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
					calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
					calendar.set(Calendar.MINUTE, minute);
					
					EditText timeEditText = (EditText) findViewById(R.id.note_edit_time_field);
					timeEditText.setText(
							DateTimeUtil
								.dateToStandardDateTimeString(
											calendar.getTime()));
				}
			};
			
	private class SaveSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			
			Intent result = new Intent();
			result.putExtra(getString(R.string.extra_animal_object), animal);
			result.putExtra(getString(R.string.extra_note_object), note);
			result.putExtra(getString(R.string.extra_note_title_type), titleNoteType);
			result.putExtra(getString(R.string.extra_note_base_rest_path), baseRestPath);
			
			setResult(ResultUtil.RESULT_SUCCESS, result);
			finish();
		}
		
	}
}
